package com.qding.park.manager.service.core.facade.impl.common;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qding.park.common.core.cache.service.CacheServiceFacade;
import com.qding.park.common.core.exceptions.BaseException;
import com.qding.park.common.core.exceptions.ExceptionMessage;
import com.qding.park.common.core.exceptions.business.adapter.AdapterException;
import com.qding.park.common.core.exceptions.business.manager.adapterfactory.AdapterProxyCreateFail;
import com.qding.park.common.core.exceptions.business.manager.service.ServiceCoreException;
import com.qding.park.common.utils.DateUtils;
import com.qding.park.common.utils.ListUtil;
import com.qding.park.manager.common.pojo.ParkDataResult;
import com.qding.park.manager.facade.core.service.common.ReserveCommonFacade;
import com.qding.park.manager.pojo.ReserveParams;
import com.qding.park.manager.pojo.TbReserve;
import com.qding.park.manager.pojo.ap.ApReservationInReminder;
import com.qding.park.manager.pojo.example.TbReserveExample;
import com.qding.park.manager.pojo.example.TbReserveExample.Criteria;
import com.qding.park.manager.service.core.biz.ReserveBiz;
import com.qding.park.manager.service.core.mapper.TbReserveMapper;


@Service("reserveCommonFacade")
public class ReserveCommonFacadeImpl implements ReserveCommonFacade {
    
    @Autowired
    private ReserveBiz reserveBiz;
    
    @Autowired
    private TbReserveMapper tbReserveMapper;
    
    @Autowired
    private CacheServiceFacade cacheServiceFacade;

    @Override
    public ParkDataResult list(TbReserveExample example, int jumpPage, int pageLength) {
     // 得到第一个统计条件
        Criteria criteria = example.getOredCriteria().get(0);
        // 过滤预定单
        criteria.andReserverTypeIsRes();
        
        //只选择有效的状态
        criteria.andEffectiveStatu();
        // 排序
        example.orderByCreateTimeDesc();

        PageHelper.startPage(jumpPage, pageLength);
        // 统计预定单
        List<TbReserve> reservelist = tbReserveMapper.reserveListByExample(example);

        PageInfo page = new PageInfo(reservelist);
        List dataList = new ArrayList();
        
        int totalFee=0;
        for (TbReserve reserve : reservelist) {
            
            Map<String, Object> map = new HashMap<String, Object>();
            // 订单号
            map.put("orderId", reserve.getId());
            // 订单状态
            map.put("orderStatus", reserveBiz.getOrderStatusStr(reserve));
            // 手机号
            map.put("tel", reserve.getTel());
            // 车牌
            map.put("carNum", reserve.getCarNum());
            // 预定车场
            map.put("appointmentParkName", reserve.getParkName());
            // 计算押金
//          reserve.setDeposit(reserveBiz.getOrderFee(reserve));
            // 预定押金
            map.put("appointmentFee", reserve.getDeposit());

            // 预定开始时间
            map.put("startTime", reserve.getStartTime() == null ? ""
                    : DateUtils.formatDate(reserve.getStartTime(), DateUtils.DATE_FORMAT_DATETIME));
            // 预定结束时间
            map.put("endTime", reserve.getEndTime() == null ? ""
                    : DateUtils.formatDate(reserve.getEndTime(), DateUtils.DATE_FORMAT_DATETIME));

            // 当前状态
            map.put("currentStatus", reserveBiz.getCurrentStatus(reserve));
            totalFee=totalFee+reserve.getDeposit();
            dataList.add(map);
        }
        
//      Map<String,Object> dataMap=new LinkedHashMap<String,Object>();
//      dataMap.put("list", dataList);
//      dataMap.put("tatalFee", totalFee);
        ParkDataResult parkDataResult = ParkDataResult.createObjDate();
        parkDataResult.putDataOnObj("list", dataList);
        parkDataResult.putDataOnObj("totalFee", totalFee);
        parkDataResult.putDataOnObj("currentPage", page.getPageNum());
        parkDataResult.putDataOnObj("numPerPage", page.getPageSize());
        parkDataResult.putDataOnObj("totalCount", page.getTotal());
        parkDataResult.putDataOnObj("hast", page.isHasPreviousPage());
        parkDataResult.putDataOnObj("next", page.isHasNextPage());
        return parkDataResult;
    }

    @Override
    public void reservePayedIssuedFailRollBack(TbReserve tbReserve) {
        reserveBiz.issuedFailRollBack(tbReserve);
    }

    @Override
    public ParkDataResult reserveParams_set(ReserveParams params, int parkId) {
        reserveBiz.setReserveParams(params, parkId);
        ParkDataResult parkDataResult = ParkDataResult.createEmpty();
        return parkDataResult;
    }

    @Override
    public ParkDataResult queryReservesByBjuserId(String bjuserid) throws ServiceCoreException {
        List<TbReserve> reserves = reserveBiz.queryReservesByBjuserId(bjuserid);

        if (ListUtil.isEmpty(reserves)) {
            return ParkDataResult.createEmpty();
        }

        List list = new ArrayList();
        for (TbReserve record : reserves) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("carNum", record.getCarNum());
            map.put("reserveId", record.getId());
            map.put("parkId", record.getParkID());
            map.put("parkName", record.getParkName());
            map.put("reserveTime", record.getEndTime() == null ? 0 : record.getEndTime().getTime() / 1000);
            map.put("deposit", record.getDeposit());
            list.add(map);
        }
        ParkDataResult parkDataResult = ParkDataResult.createListDate();
        parkDataResult.putDataOnList(list);
        return parkDataResult;
    }

    @Override
    public ParkDataResult reserveParams(int parkId) throws BaseException {
        ReserveParams params = reserveBiz.queryReserveParams(parkId);
        if (params == null) {
            throw new ServiceCoreException(ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_PARK.getId(), null,
                    ExceptionMessage.createExceptionMessage(
                            ServiceCoreException.TypeEnum.EXCEPTION_NOFIND_PARK.getDesc(), "没有找到对应的车场信息",
                            "parkId=" + parkId));
        }
        ParkDataResult parkDataResult = ParkDataResult.createObjDate();
        parkDataResult.putDataOnObj("appointmentTime", params.getAppointmentTime());
        parkDataResult.putDataOnObj("appointmentFee", params.getAppointmentFee());
        return parkDataResult;
    }

    @Override
    public ParkDataResult queryReservesInfoById(String reserveId) {
        TbReserve tbReserve = reserveBiz.queryReservesInfoById(reserveId);

        if (tbReserve == null) {
            return ParkDataResult.createEmpty();
        }
        ParkDataResult parkDataResult = ParkDataResult.createObjDate();
        parkDataResult.putDataOnObj("carNum", tbReserve.getCarNum());
        parkDataResult.putDataOnObj("reserveId", tbReserve.getId());
        parkDataResult.putDataOnObj("parkId", tbReserve.getParkID());
        parkDataResult.putDataOnObj("parkName", tbReserve.getParkName());
        parkDataResult.putDataOnObj("reserveTime",
                tbReserve.getStartTime() == null ? 0 : tbReserve.getStartTime().getTime() / 1000);
        return parkDataResult;
    }

    @Override
    public TbReserve queryReservedByBjuserId(int supplyID, String parkCode, String carNum) {
        return reserveBiz.queryReservedByBjuserId(supplyID, parkCode, carNum);
    }

    @Override
    public void carInCheck(ApReservationInReminder apReservationInReminder) throws BaseException {
        reserveBiz.carInCheck(apReservationInReminder);

    }

    @Override
    public void reserveTimeOut(TbReserve tbReserve) throws AdapterProxyCreateFail, AdapterException {
        reserveBiz.reserveTimeOut(tbReserve);

    }

    @Override
    public void reserveDelayTimeOut(TbReserve tbReserve) throws BaseException {
        reserveBiz.reserveDelayTimeOut(tbReserve);

    }

    @Override
    public void reservePayedHandle(TbReserve tbReserve) throws BaseException {
        reserveBiz.reservePayedHandle(tbReserve);

    }

    @Override
    public ParkDataResult createReserveOrder(String bjuserId, int parkId, String carNum, Date reserveStartTime)
            throws BaseException {
     // TODO Auto-generated method stub
        TbReserve tbReserve = new TbReserve();
        tbReserve.setCarNum(carNum);
        tbReserve.setStartTime(reserveStartTime);
        tbReserve.setBjuserId(bjuserId);
        tbReserve.setParkID(parkId);
        reserveBiz.createReserveOrder(tbReserve);

        ParkDataResult parkDataResult = new ParkDataResult();
        parkDataResult.putDataOnObj("szOrderId", tbReserve.getId());
        parkDataResult.putDataOnObj("bjOrderId", tbReserve.getBjOrderId());
        // 下发预定单
        return parkDataResult;
    }

    @Override
    public ParkDataResult cancelResecancelById(String reserveId) throws BaseException {
        int num = reserveBiz.cancelReservesById(reserveId);

        if (num == 1) {
            /*********** 从监控列表中删除 ***************************/
            cacheServiceFacade.reserve_monitor_delete(reserveId);
            /*********** 从监控列表中删除 ***************************/
        }
        // ParkDataResult parkDataResult=ParkDataResult.createObjDate();
        return ParkDataResult.createEmpty();
    }

}
